<template>
  <div id="app">
    <editor
      id="tinymce"
      v-model="myValue"
      :disabled="disabled"
      :init="einit"
      @onInit="handleInit"
    />
  </div>
</template>

<script>
import Cos from '@/utils/cosUpload'
import { Message as message } from 'element-ui'
import tinymce from 'tinymce/tinymce'
import Editor from '@tinymce/tinymce-vue'
import 'tinymce/plugins/image'
import 'tinymce/plugins/imagetools'
import 'tinymce/plugins/searchreplace'
import 'tinymce/plugins/link'// 插入链接
import 'tinymce/plugins/code'// 插入代码
import 'tinymce/plugins/preview'// 插入预览
import 'tinymce/plugins/table'// 插入表格插件
import 'tinymce/plugins/wordcount' // 字数统计插件
import 'tinymce/plugins/fullscreen' // 全屏
import 'tinymce/plugins/lists'// 列表插件
import 'tinymce/skins/ui/oxide/skin.min.css' // 富文本样式
import 'tinymce/icons/default' // 富文本样式
import 'tinymce/themes/mobile/theme'
// 配置富文本
import 'tinymce/themes/silver/theme.min.js' // 引入富文本的主要脚本
export default {
  name: 'App',
  components: { Editor },
  props: {
    value: {
      type: String,
      default: ''
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      myValue: this.value,
      einit: {
        zIndex: 999999,
        placeholder: '请输入内容',
        skin_url: require('@/assets/skins/ui/oxide/skin.min.css'),
        language_url: require('@/assets/langs/zh_CN.js'),
        language: 'zh_CN',
        height: 400,
        object_resizing: 'img',
        menubar: true,
        branding: false,
        paste_data_images: true, // 允许粘贴图像
        toolbar: 'fullscreen | undo redo | formatselect alignleft aligncenter alignright alignjustify | link unlink | numlist bullist | image media table | fontselect fontsizeselect forecolor backcolor | bold italic underline strikethrough | indent outdent | superscript subscript | removeformat ｜',
        toolbar_drawer: 'sliding',
        quickbars_selection_toolbar: 'removeformat | bold italic underline strikethrough | fontsizeselect forecolor backcolor',
        plugins: ['table lists link image imagetools code codesample anchor emoticons wordcount preview fullpage fullscreen'],
        images_upload_handler: function(blobInfo, success, failure, progress) {
          Cos.init.putObject({ // 此处用了最简单的上传函数，此外，腾讯云还支持分片上传函数等等。
            Bucket: Cos.config.Bucket, // 存储桶名称
            Region: Cos.config.Region, // 地区
            Key: 'pic/' + blobInfo.filename(), // 图片名称
            StorageClass: 'STANDARD',
            Body: blobInfo.blob(), // 上传文件对象
            onHashProgress: function(progressData) {
              console.log('校验中', progressData)
            },
            onProgress: function(progressData) {
              console.log('上传中', progressData)
            }
          },
          async function(err, data) {
            if (!err) {
              success('https://' + data.Location)
            } else {
              message.error('上传文件到 Cos 失败')
            }
            console.log(err, data)
            // 这里的data如果是个带有Location等的对象，则说明上传成功。
            // if (!err) {
            //   try {
            //     const param = new FormData()
            //     param.append('group_id', me.fileForm.group_id)
            //     param.append('type', me.fileForm.fileType)
            //     param.append('url', 'https://' + data.Location)
            //     param.append('sha1', data.ETag)
            //     param.append('filename', me.fileForm.filename)
            //     param.append('mimetype', data.Location.split('.').pop())
            //     param.append('filesize', me.file.size)
            //     const { code, message } = await material_add(param)
            //     if (!code) {
            //       me.close()
            //       me.$parent.loadData()
            //       me.$message.success(message)
            //     } else {
            //       me.$message.warning(message)
            //     }
            //   } catch (error) {
            //     console.error(error)
            //   } finally {
            //     // eslint-disable-next-line require-atomic-updates
            //     me.loading = false
            //   }
            // } else {
            //   me.$message.error('上传文件到 Cos 失败')
            //   me.loading = false
            // }
          })
          // var xhr, formData
          // xhr = new XMLHttpRequest()
          // xhr.withCredentials = false
          // xhr.open('POST', axios.defaults.baseURL + '/base/upload/upload_image')
          // xhr.upload.onprogress = function(e) {
          //   progress(e.loaded / e.total * 100)
          // }

          // xhr.onload = function() {
          //   var result
          //   if (xhr.status === 403) {
          //     failure('HTTP Error: ' + xhr.status, { remove: true })
          //     return
          //   }
          //   if (xhr.status < 200 || xhr.status >= 300) {
          //     failure('HTTP Error: ' + xhr.status)
          //     return
          //   }

          //   result = JSON.parse(xhr.responseText)
          //   if (result.errorCode !== 0) {
          //     failure('上传出错：' + xhr.responseText)
          //     return
          //   }
          //   success(result.data)
          // }

          // xhr.onerror = function() {
          //   failure('Image upload failed due to a XHR Transport error. Code: ' + xhr.status)
          // }

          // formData = new FormData()
          // formData.append('upfile', blobInfo.blob(), blobInfo.filename())

          // xhr.send(formData)
        }
      },
      content: '',
      isPreView: false,
      tinymceEdit: null
    }
  },
  watch: {
    value(newValue) {
      this.myValue = newValue
    },
    myValue(newValue) {
      this.$emit('input', newValue)
    }
  },
  mounted() {
    tinymce.init({
      // selector: 'tinymce',
      // placeholder: 'Ask a question or post an update...',
      // menubar: false,
      // skin: 'outside',
      // toolbar_location: 'bottom'
    })
  },
  methods: {
    handleInit(event, editor) {
      // 初始化的时候把 editor 对象保存，方便调用API
      this.tinymceEdit = editor
    }
  }
}
</script>

<style lang="scss" scoped>
.htmlContent {
  border: 1px solid rgba(238, 238, 238, 1);
}

// .htmlContent /deep/ img {
//   max-width: 375px;
// }
</style>
